import React from 'react';
import PropTypes from 'prop-types';
import {Card, Button, Row, Col, Form, Spin, Table, Collapse} from 'antd';
import routes from './routes';
import {updateValidator} from './validator';
import Return from '../common/Return';
import {FORM_OPTIONS, TABLE} from '../constants';
import {getDetail, settingData} from './api';
import {agentKind, currency, saleOrderPriceTerms, saleOrderType, saleOrderTransportType, paymentType} from '../Enum';
import styles from './style.css';
import {conventEnumValueToString, formatDateTime} from '../utils';
import {uuid} from './utils';
import {injectIntl} from './intl';
import WrappedInputNumber from '../common/WrappedInputNumber';
import InputPercent from '../common/InputPercent';
const FormItem = Form.Item;
const {Panel} = Collapse;
export class SettingPanel extends React.PureComponent {
    state = {
        isValidate: false,
        hasOperat: false,
        loading: false,
        detailId: '',
        data: {},
        dealerSaleInformationDetails: [],
    }
   
    componentDidMount() {
        if(this.props.id)
            this.getDetailInfo();
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    getDetailInfo = () => {
        const id = this.props.id;
        this.setState({loading: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data,
                        dealerSaleInformationDetails: res.data.dealerSaleInformationDetails || [],
                    });
                else
                    this.setState(({
                        loading: false
                    }));
            });
    }
    onSubmit = () => {
        this.setState({
            loading: true
        });
        const {data, dealerSaleInformationDetails} = this.state;
        const condition = {
            rowVersion: data.rowVersion,
            dealerSaleInformationDetails: (dealerSaleInformationDetails || []).map(v => ({
                id: v.id,
                theoreticalStoreSaleRatio: v.theoreticalStoreSaleRatio,
                deliveryPlanDeliveryCycleMonth: v.deliveryPlanDeliveryCycleMonth,
                receiveDeliveryCycleMonth: v.receiveDeliveryCycleMonth,
                inTransitDeliveryCycleMonth: v.inTransitDeliveryCycleMonth,
            })),
        };
        settingData(data.id, condition).then(res => {
            if(res.ok)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onClickReturnBtn = () => {
        this.props.onCancel();
    }
    onClickAddDetailBtn = () => {
        const details = this.state.dealerSaleInformationDetails;
        this.setState({
            dealerSaleInformationDetails: [
                ...details,
                {
                    id: uuid(),
                    isNeedApproved: null
                }
            ],
            hasOperat: true
        });
    };
    onDealerPartInformationChange = (value, name, id) => {
        const details = this.state.dealerSaleInformationDetails || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    [name]: value,
                });
            return d;
        });
        this.setState({
            dealerSaleInformationDetails: tmp,
            hasOperat: true
        });
    }
    render() {
        const {data, dealerSaleInformationDetails} = this.state;
        const {formatMessage} = this.props.intl;
        const partInformationColumns = [{
            title: (<span className="ant-form-item-required">{formatMessage({
                id: 'settingPanel.column.brand',
                defaultMessage: '品牌'
            })}</span>
            ),
            width: 150,
            dataIndex: 'brandCode',
        }, {
            title: (<span className="ant-form-item-required">{formatMessage({
                id: 'settingPanel.column.tradeMethod',
                defaultMessage: '贸易方式'
            })}</span>
            ),
            width: 150,
            dataIndex: 'tradeMethodName',
        }, {
            title: formatMessage({
                id: 'settingPanel.column.priceClause',
                defaultMessage: '价格条款'
            }),
            width: 120,
            dataIndex: 'priceClause',
            render: text => conventEnumValueToString(saleOrderPriceTerms, text)
        }, {
            title: formatMessage({
                id: 'settingPanel.column.currency',
                defaultMessage: '结算币种'
            }),
            width: 120,
            dataIndex: 'currency',
            render: text => conventEnumValueToString(currency, text)
        }, {
            title: formatMessage({
                id: 'settingPanel.column.orderType',
                defaultMessage: '订单类型'
            }),
            width: 120,
            dataIndex: 'orderType',
            render: text => conventEnumValueToString(saleOrderType, text)
        }, {
            title: formatMessage({
                id: 'settingPanel.column.transportType',
                defaultMessage: '运输方式'
            }),
            width: 120,
            dataIndex: 'transportType',
            render: text => conventEnumValueToString(saleOrderTransportType, text)
        }, {
            title: formatMessage({
                id: 'settingPanel.column.paymentType',
                defaultMessage: '付款方式'
            }),
            width: 120,
            dataIndex: 'paymentType',
            render: text => conventEnumValueToString(paymentType, text)
        }, {
            title: formatMessage({
                id: 'settingPanel.column.account',
                defaultMessage: '到付账号'
            }),
            dataIndex: 'account',
        }, {
            title: formatMessage({
                id: 'settingPanel.column.carrier',
                defaultMessage: '货代名称'
            }),
            width: 150,
            dataIndex: 'carrierName',
        }, {
            title: formatMessage({
                id: 'settingPanel.column.shippingPort',
                defaultMessage: '发运港口'
            }),
            width: 150,
            dataIndex: 'shippingPortName',
        }, {
            title: formatMessage({
                id: 'settingPanel.column.destinationPort',
                defaultMessage: '目的港口'
            }),
            dataIndex: 'destinationPort',
        }, {
            title: formatMessage({
                id: 'settingPanel.column.deliveryDate',
                defaultMessage: '需求交期'
            }),
            dataIndex: 'deliveryDate',
        }, {
            title: formatMessage({
                id: 'settingPanel.column.theoreticalStoreSaleRatio',
                defaultMessage: '理论总存销比'
            }),
            dataIndex: 'theoreticalStoreSaleRatio',
            render: (text, record) => (
                <FormItem>
                    <InputPercent
                        min={0}
                        precision={4}
                        name="theoreticalStoreSaleRatio"
                        value={record.theoreticalStoreSaleRatio}
                        onBlur={value => this.onDealerPartInformationChange(value, 'theoreticalStoreSaleRatio', record.id)} />
                </FormItem>
            )
        }, {
            title: formatMessage({
                id: 'settingPanel.column.deliveryPlanDeliveryCycleMonth',
                defaultMessage: '发运计划物流周期月数'
            }),
            dataIndex: 'deliveryPlanDeliveryCycleMonth',
            render: (text, record) => (
                <FormItem>
                    <WrappedInputNumber
                        min={0}
                        precision={0}
                        name="deliveryPlanDeliveryCycleMonth"
                        value={record.deliveryPlanDeliveryCycleMonth}
                        onBlur={value => this.onDealerPartInformationChange(value, 'deliveryPlanDeliveryCycleMonth', record.id)} />
                </FormItem>
            )
        }, {
            title: formatMessage({
                id: 'settingPanel.column.receiveDeliveryCycleMonth',
                defaultMessage: '新到货物流周期月数'
            }),
            dataIndex: 'receiveDeliveryCycleMonth',
            render: (text, record) => (
                <FormItem>
                    <WrappedInputNumber
                        min={0}
                        precision={0}
                        name="receiveDeliveryCycleMonth"
                        value={record.receiveDeliveryCycleMonth}
                        onBlur={value => this.onDealerPartInformationChange(value, 'receiveDeliveryCycleMonth', record.id)} />
                </FormItem>
            )
        }, {
            title: formatMessage({
                id: 'settingPanel.column.inTransitDeliveryCycleMonth',
                defaultMessage: '在途物流周期月数'
            }),
            dataIndex: 'inTransitDeliveryCycleMonth',
            render: (text, record) => (
                <FormItem>
                    <WrappedInputNumber
                        min={0}
                        precision={0}
                        name="inTransitDeliveryCycleMonth"
                        value={record.inTransitDeliveryCycleMonth}
                        onBlur={value => this.onDealerPartInformationChange(value, 'inTransitDeliveryCycleMonth', record.id)} />
                </FormItem>
            )
        }, {
            title: formatMessage({
                id: 'settingPanel.column.kdPackingAttribute',
                defaultMessage: 'KD包装属性'
            }),
            dataIndex: 'kdPackingAttribute',
        }, {
            title: formatMessage({
                id: 'settingPanel.column.pdIExpenseStandard',
                defaultMessage: 'PDI费用标准'
            }),
            dataIndex: 'pdiExpenseStandard',
        }, {
            title: (<span>{formatMessage({
                id: 'settingPanel.column.remark',
                defaultMessage: '备注'
            })}</span>
            ),
            dataIndex: 'remark',
        }, {
            title: (<span className="ant-form-item-required">{formatMessage({
                id: 'settingPanel.column.effectiveDate',
                defaultMessage: '生效日期'
            })}</span>
            ),
            dataIndex: 'effectiveDate',
            render: text => formatDateTime(text)
        }, {
            title: (<span>{formatMessage({
                id: 'settingPanel.column.expirationDate',
                defaultMessage: '失效日期'
            })}</span>
            ),
            dataIndex: 'expirationDate',
            render: text => formatDateTime(text)
        }];

        return (
            <div>
                <Spin spinning={this.state.loading}>
                    <Collapse className={styles.collapseMarginTop}>
                        <Panel header={<Form className="form-standard"><Row>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({
                                    id: 'settingPanel.data.code',
                                    defaultMessage: '编号'
                                })}{...FORM_OPTIONS.item} >
                                    {data.code}
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({
                                    id: 'settingPanel.data.name',
                                    defaultMessage: '名称'
                                })}{...FORM_OPTIONS.item} >
                                    {data.name}
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({
                                    id: 'settingPanel.data.shortCode',
                                    defaultMessage: '简码'
                                })}{...FORM_OPTIONS.item} >
                                    {data.shortCode}
                                </FormItem>
                            </Col></Row></Form>}>
                            <Form className="form-standard">
                                <Row>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'settingPanel.data.shortName',
                                            defaultMessage: '简称'
                                        })}{...FORM_OPTIONS.item} >
                                            {data.shortName}
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'settingPanel.data.kind',
                                            defaultMessage: '总代分类'
                                        })}{...FORM_OPTIONS.item} >
                                            {conventEnumValueToString(agentKind, data.kind)}
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'settingPanel.data.area',
                                            defaultMessage: '国际区域'
                                        })}{...FORM_OPTIONS.item} >
                                            {data.area}
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'settingPanel.data.country',
                                            defaultMessage: '国家'
                                        })}{...FORM_OPTIONS.item} >
                                            {data.country}
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'settingPanel.data.province',
                                            defaultMessage: '省份'
                                        })}{...FORM_OPTIONS.item} >
                                            {data.province}
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'settingPanel.data.city',
                                            defaultMessage: '城市'
                                        })}{...FORM_OPTIONS.item} >
                                            {data.city}
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'settingPanel.data.contactNumber',
                                            defaultMessage: '联系电话'
                                        })}{...FORM_OPTIONS.item} >
                                            {data.contactNumber}
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'settingPanel.data.fax',
                                            defaultMessage: '传真'
                                        })}{...FORM_OPTIONS.item} >
                                            {data.fax}
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'settingPanel.data.address',
                                            defaultMessage: '联系地址'
                                        })}{...FORM_OPTIONS.item} >
                                            {data.address}
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'settingPanel.data.zipCode',
                                            defaultMessage: '邮政编码'
                                        })}{...FORM_OPTIONS.item} >
                                            {data.zipCode}
                                        </FormItem>
                                    </Col>
                                </Row>
                            </Form>
                        </Panel>
                    </Collapse>
                    <Form className="form-standard">
                        <Card
                            title={formatMessage({
                                id: 'settingPanel.saleInformationDetail',
                                defaultMessage: '总代整车业务清单'
                            })}>
                            <Table
                                className="white-space-nowrap"
                                columns={partInformationColumns}
                                rowKey="id"
                                pagination={false}
                                dataSource={dealerSaleInformationDetails}
                                {...TABLE} />
                        </Card>
                    </Form>
                    <Card>
                        <Row>
                            <Col className="col-align-right">
                                <Button key="submit"
                                    onClick={this.onSubmit}
                                    type="primary"
                                    loading={this.state.loading}>
                                    {formatMessage({
                                        id: 'settingPanel.btn.submit',
                                        defaultMessage: '保存'
                                    })}</Button>
                            </Col>
                        </Row>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        onConfirm={this.onClickReturnBtn}
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

SettingPanel.propTypes = {
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {tableSearch} from './actions';

const mapDispatchToProps = (dispatch, props) => ({
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(null, mapDispatchToProps)(injectIntl(SettingPanel));
